package com.zbf.moredb.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/24  13:46
 * 描述:
 */
@Configuration
@MapperScan(basePackages = {"com.zbf.moredb.dao1"},sqlSessionFactoryRef="sqlSessionFactory1")
public class DataSource1Config {

    @Autowired
     private DataSource1Properties dataSource1Properties;

    @Bean("dataSource1")
    @Primary
    public DataSource getDataSource1(DataSource1Properties dataSource1Properties){

        DataSource build = DataSourceBuilder.create().url(dataSource1Properties.getUrl())
                .username(dataSource1Properties.getUsername())
                .password(dataSource1Properties.getPassword())
                .driverClassName(dataSource1Properties.getDriverClassName())
                .build();
        return build;
    }


    @Primary
    @Bean("transactionManager1")
    public DataSourceTransactionManager getDataSourceTransactionManager1(@Qualifier("dataSource1") DataSource dataSource){

        DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);

        return dataSourceTransactionManager;

    }

    @Primary
    @Bean("sqlSessionFactory1")
   public SqlSessionFactory getSqlSessionFactory(@Qualifier("dataSource1") DataSource dataSource) throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:/mapper/db1/*.xml"));

        return sqlSessionFactoryBean.getObject();

   }

}
